package com.jiutong.meipenggang.base;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.jiutong.meipenggang.R;
import com.jiutong.meipenggang.common.Constants;
import com.jiutong.meipenggang.http.model.interfaces.CheckLoginInterface;
import com.jiutong.meipenggang.ui.activitys.GuideActivity;
import com.jiutong.meipenggang.ui.activitys.LoginActivity;
import com.jiutong.meipenggang.ui.activitys.LoginedActivity;
import com.jiutong.meipenggang.utils.NetworkUtil;
import com.jiutong.meipenggang.utils.PermissionsResultListener;
import com.jiutong.meipenggang.utils.SpConfig;
import com.jiutong.meipenggang.views.dialog.BaseDialog;
import com.jiutong.meipenggang.views.x5webview.X5WebView;

import butterknife.ButterKnife;

/**
 * @author Veken
 */
public abstract class BaseActivity extends AppCompatActivity {

    protected static Context mContext;
    public String TAG = this.getClass().getSimpleName();
    public static final int MSG_CODE = 1;
    protected ImmersionBar mImmersionBar;
    private BaseDialog baseDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //沉浸式状态栏，设置window模式
//        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(getLayoutResouceId());
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);

        //激活沉浸式状态栏  第三方库ImmersionBar
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }

        mContext = this;

        //禁止横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        initDate(savedInstanceState);
        initView();
        initEvent();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SpConfig.getInstance().getBool(Constants.TOKEN_FAIL)) {
            showLoginDialog();
        }
    }

    private PermissionsResultListener mListener;

    private int mRequestCode;

    /**
     * 其他 Activity 继承 BaseActivity 调用 performRequestPermissions 方法
     * <p>
     * //     * @param desc        首次申请权限被拒绝后再次申请给用户的描述提示
     *
     * @param permissions 要申请的权限数组
     * @param requestCode 申请标记值
     * @param listener    实现的接口
     */
    protected void performRequestPermissions(String[] permissions, int requestCode, PermissionsResultListener listener) {
        if (permissions == null || permissions.length == 0) {
            return;
        }
        mRequestCode = requestCode;
        mListener = listener;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查是否声明了权限
            if (checkEachSelfPermission(permissions)) {
                requestEachPermissions(permissions, requestCode);
            } else {// 已经申请权限
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            }
        } else {
            if (mListener != null) {
                mListener.onPermissionGranted();
            }
        }
    }

    /**
     * 申请权限前判断是否需要声明
     *
     * @param permissions
     * @param requestCode
     */
    private void requestEachPermissions(String[] permissions, int requestCode) {
        //申请权限前判断是否需要声明的dialog，默认不需要
//        if (shouldShowRequestPermissionRationale(permissions)) {// 需要再次声明
//            showRationaleDialog(permissions, requestCode);
//        } else {
        ActivityCompat.requestPermissions(this, permissions, requestCode);
//        }
    }

    /**
     * 弹出声明的 Dialog
     *
     * @param permissions
     * @param requestCode
     */
    private void showRationaleDialog(final String[] permissions, final int requestCode) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("")
                .setMessage("请记得添加权限哦！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        ActivityCompat.requestPermissions(BaseActivity.this, permissions, requestCode);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }

    /**
     * 再次申请权限时，是否需要声明
     *
     * @param permissions
     * @return
     */
    private boolean shouldShowRequestPermissionRationale(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检察每个权限是否申请
     *
     * @param permissions
     * @return true 需要申请权限,false 已申请权限
     */
    private boolean checkEachSelfPermission(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }

    /**
     * 申请权限结果的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            if (checkEachPermissionsGranted(grantResults)) {
                if (mListener != null) {
                    mListener.onPermissionGranted();
                }
            } else {// 用户拒绝申请权限
                if (mListener != null) {
                    mListener.onPermissionDenied();
                }
            }
        }
    }

    /**
     * 检查回调结果
     *
     * @param grantResults
     * @return
     */
    private boolean checkEachPermissionsGranted(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 还未登录，显示去登录dialog
     */
    public void showLoginDialog() {
        if (baseDialog == null) {
            baseDialog = new BaseDialog.Builder().
                    layResuorce(R.layout.dialog_common).
                    cancelViewClickEvent(R.id.tv_dialog_cancel).
                    okViewClickEvent(R.id.tv_dialog_ok).
                    confirmId(R.id.tv_dialog_confirm).
                    llBottomId(R.id.ll_dialog).
                    contentTextId(R.id.tv_dialog_content).
                    hintTextId(R.id.tv_dialog_hint).
                    setHintText("温馨提示").
                    setContentText("token失效，请重新登录").
                    setCancelText("否").
                    setOkText("是").
                    showOneOrTwoBtn(false).
                    setConfirmText("确定").
                    gravityStyle(Gravity.CENTER).
                    animResource(R.style.dialog_animation_fade).
                    dialogWidth(-2).
                    build();
            baseDialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                @Override
                public void onOkClick() {
                    baseDialog.dismiss();
                    if (TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.USERNAME_STRING))) {
                        openActivity(LoginActivity.class);
                    } else {
                        openActivity(LoginedActivity.class);
                    }
                    SpConfig.getInstance().edit().putBoolean(Constants.TOKEN_FAIL,false).commit();
                }

                @Override
                public void onOk2Click() {

                }
            });
        }

        baseDialog.show(getSupportFragmentManager(), "login");
    }



    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    /**
     * 初始化沉浸式
     */
    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar
                .statusBarDarkFont(true, 0.2f)
                .fitsSystemWindows(true)
                //单独指定软键盘模式
                .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
                .keyboardEnable(true)
                //软键盘监听回调
                .setOnKeyboardListener(new OnKeyboardListener() {
                    @Override
                    public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                        LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                    }
                })
                .init();
    }

    /**
     * 子Acitivty的布局xml
     *
     * @return
     */
    public abstract int getLayoutResouceId();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        ButterKnife.unbind(this);
    }

    protected void initView() {
    }

    protected void initDate(Bundle savedInstanceState) {
    }

    protected void initEvent() {
    }

    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    /**
     * 通过类名启动Activity，并且含有Bundle数据
     *
     * @param pClass
     * @param pBundle
     */
    public void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(this, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }

        if (pClass.isAnnotationPresent(CheckLoginInterface.class)) {

            if (TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.SESSIONID_STRING))) {
                intent = new Intent(this, LoginActivity.class);
            }
        }

        startActivity(intent);
    }

    /**
     * Toast提示
     *
     * @param str
     */
    public void toastShortShow(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

    public void toastLongShow(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_LONG).show();
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    protected void isLogin() {
        if (TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.USERNAME_STRING))) {
            openActivity(LoginActivity.class);
        } else if (!TextUtils.isEmpty(SpConfig.getInstance().getString(Constants.USERNAME_STRING))
                && !SpConfig.getInstance().getBool(Constants.IS_LOGIN)) {
            openActivity(LoginedActivity.class);
        }
    }

}
